
// src/main/java/com/xxxy/ljh/myapplication/DaoImpl/UserDaoImpl.java
package com.xxxy.ljh.myapplication.DaoImpl;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xxxy.ljh.myapplication.Dao.UserDao;
import com.xxxy.ljh.myapplication.Dao.UserDao;
import com.xxxy.ljh.myapplication.Manager.UserManager;
import com.xxxy.ljh.myapplication.dphelper.sqliteDBHelper;
import com.xxxy.ljh.myapplication.model.User;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户数据访问接口实现类，提供用户相关的数据库操作功能。
 */
public class UserDaoImpl implements UserDao {

    private Context mContext;
    private SQLiteDatabase mDatabase;

    /**
     * 构造方法，初始化数据库连接。
     *
     * @param context 应用上下文对象，用于创建数据库助手实例
     */
    public UserDaoImpl(Context context) {
        mContext = context;
        mDatabase = new sqliteDBHelper(mContext).getWritableDatabase();
    }

    /**
     * 注册新用户到数据库中。
     *
     * @param user 待注册的用户对象，包含用户名、密码等信息
     * @return true 表示注册成功，false 表示失败
     */
    @Override
    public boolean register(User user) {
        ContentValues values = new ContentValues();
        values.put("username", user.getUsername());
        values.put("password", user.getPassword());
        values.put("real_name", user.getRealName());
        values.put("role", 0);
        values.put("phone", user.getPhone());
        values.put("email", user.getEmail());
        values.put("student_id", user.getStudentId());
        values.put("department", user.getDepartment());

        long result = mDatabase.insert("t_user", null, values);
        return result != -1;
    }

    /**
     * 验证用户登录凭据，并在验证通过后将用户信息保存至用户管理器。
     *
     * @param username 用户名
     * @param password 密码
     * @return true 表示登录成功，false 表示失败
     */
    @Override
    public boolean login(String username, String password) {
        String selection = "username = ? AND password = ?";
        String[] selectionArgs = {username, password};
        Cursor cursor = mDatabase.query("t_user", null, selection, selectionArgs, null, null, null);
        boolean result = cursor.getCount() > 0;
        cursor.close();
        User user = getUserByUsername(username);
        if (user != null) {  // 添加空值检查
            UserManager userManager = UserManager.getInstance(mContext);
            userManager.loginUser(user);
        }
        cursor.close(); // 关闭游标释放资源
        return result;
    }

    /**
     * 检查指定用户名是否已存在于数据库中。
     *
     * @param name 要检查的用户名
     * @return true 表示该用户名已被使用，false 表示未被使用
     */
    @Override
    public boolean checkName(String name) {
        String selection = "username = ?";
        String[] selectionArgs = {name};
        Cursor cursor = mDatabase.query("t_user", null, selection, selectionArgs, null, null, null);
        boolean result = cursor.getCount() > 0;
        cursor.close();
        return result;
    }

    /**
     * 根据用户名从数据库获取对应的用户信息。
     *
     * @param username 用户名
     * @return 返回匹配的用户对象；若无匹配项则返回 null
     */
    @Override
    public User getUserByUsername(String username) {
        String selection = "username = ?";
        String[] selectionArgs = {username};
        Cursor cursor = mDatabase.query("t_user", null, selection, selectionArgs, null, null, null);

        User user = null;
        if (cursor.moveToFirst()) {
            user = new User();
            user.setUserId(cursor.getInt(cursor.getColumnIndexOrThrow("user_id")));
            user.setUsername(cursor.getString(cursor.getColumnIndexOrThrow("username")));
            user.setPassword(cursor.getString(cursor.getColumnIndexOrThrow("password")));
            user.setRealName(cursor.getString(cursor.getColumnIndexOrThrow("real_name")));
            user.setRole(cursor.getInt(cursor.getColumnIndexOrThrow("role")));
            user.setPhone(cursor.getString(cursor.getColumnIndexOrThrow("phone")));
            user.setEmail(cursor.getString(cursor.getColumnIndexOrThrow("email")));
            user.setAvatar(cursor.getString(cursor.getColumnIndexOrThrow("avatar")));
            user.setStudentId(cursor.getString(cursor.getColumnIndexOrThrow("student_id")));
            user.setDepartment(cursor.getString(cursor.getColumnIndexOrThrow("department")));
        }
        cursor.close();
        return user;
    }

    /**
     * 根据用户ID从数据库获取对应的用户信息。
     *
     * @param userId 用户唯一标识符
     * @return 返回匹配的用户对象；若无匹配项则返回 null
     */
    @Override
    public User getUserById(int userId) {
        String selection = "user_id = ?";
        String[] selectionArgs = {String.valueOf(userId)};
        Cursor cursor = mDatabase.query("t_user", null, selection, selectionArgs, null, null, null);

        User user = null;
        if (cursor.moveToFirst()) {
            user = new User();
            user.setUserId(cursor.getInt(cursor.getColumnIndexOrThrow("user_id")));
            user.setUsername(cursor.getString(cursor.getColumnIndexOrThrow("username")));
            user.setPassword(cursor.getString(cursor.getColumnIndexOrThrow("password")));
            user.setRealName(cursor.getString(cursor.getColumnIndexOrThrow("real_name")));
            user.setRole(cursor.getInt(cursor.getColumnIndexOrThrow("role")));
            user.setPhone(cursor.getString(cursor.getColumnIndexOrThrow("phone")));
            user.setEmail(cursor.getString(cursor.getColumnIndexOrThrow("email")));
            user.setAvatar(cursor.getString(cursor.getColumnIndexOrThrow("avatar")));
            user.setStudentId(cursor.getString(cursor.getColumnIndexOrThrow("student_id")));
            user.setDepartment(cursor.getString(cursor.getColumnIndexOrThrow("department")));
        }
        cursor.close();
        return user;
    }

    /**
     * 获取指定用户的权限角色。
     *
     * @param username 用户名
     * @return 返回用户的角色编号；若找不到对应用户则返回 -1
     */
    @Override
    public int getUserRoleFromDatabase(String username) {
        String[] projection = {"role"};
        String selection = "username = ?";
        String[] selectionArgs = {username};
        Cursor cursor = mDatabase.query("t_user", projection, selection, selectionArgs, null, null, null);
        int role = -1;
        if (cursor.moveToFirst()) {
            role = cursor.getInt(cursor.getColumnIndexOrThrow("role"));
        }
        cursor.close();
        return role;
    }

    /**
     * 查询并返回所有用户的信息列表。
     *
     * @return 包含所有用户信息的列表
     */
    @Override
    public List<User> getAllUsers() {
        List<User> userList = new ArrayList<>();
        Cursor cursor = mDatabase.query("t_user", null, null, null, null, null, null);

        while (cursor.moveToNext()) {
            User user = new User();
            user.setUserId(cursor.getInt(cursor.getColumnIndexOrThrow("user_id")));
            user.setUsername(cursor.getString(cursor.getColumnIndexOrThrow("username")));
            user.setPassword(cursor.getString(cursor.getColumnIndexOrThrow("password")));
            user.setRealName(cursor.getString(cursor.getColumnIndexOrThrow("real_name")));
            user.setRole(cursor.getInt(cursor.getColumnIndexOrThrow("role")));
            user.setPhone(cursor.getString(cursor.getColumnIndexOrThrow("phone")));
            user.setEmail(cursor.getString(cursor.getColumnIndexOrThrow("email")));
            user.setAvatar(cursor.getString(cursor.getColumnIndexOrThrow("avatar")));
            user.setStudentId(cursor.getString(cursor.getColumnIndexOrThrow("student_id")));
            user.setDepartment(cursor.getString(cursor.getColumnIndexOrThrow("department")));
            userList.add(user);
        }
        cursor.close();
        return userList;
    }

    /**
     * 更新数据库中的用户信息。
     *
     * @param user 包含更新后的用户信息的对象
     * @return true 表示更新成功，false 表示失败
     */
    @Override
    public boolean updateUser(User user) {
        ContentValues values = new ContentValues();
        values.put("username", user.getUsername());
        values.put("password", user.getPassword());
        values.put("real_name", user.getRealName());
        values.put("role", user.getRole());
        values.put("phone", user.getPhone());
        values.put("email", user.getEmail());
        values.put("avatar", user.getAvatar());
        values.put("student_id", user.getStudentId());
        values.put("department", user.getDepartment());

        String whereClause = "user_id = ?";
        String[] whereArgs = {String.valueOf(user.getUserId())};

        int result = mDatabase.update("t_user", values, whereClause, whereArgs);
        return result > 0;
    }
}